package carson.web.mvc;

import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


/**
 * 根据文件路径将文件发送到响应
 *
 * @author Carson Chen
 */
public class FilePathResult extends AbstractFileResult {

    /**
     * 实例化FilePathResult
     *
     * @param filePath    文件路径
     * @param contentType 内容类型
     */
    public FilePathResult(String filePath, String contentType) {
        super(contentType);
        this.filePath = filePath;
    }

    /**
     * 实例化FilePathResult
     *
     * @param filePath         文件路径
     * @param contentType      内容类型
     * @param fileDownloadName 下载时的文件名称
     */
    public FilePathResult(String filePath, String contentType, String fileDownloadName) {
        super(contentType);
        this.filePath = filePath;
        setFileDownloadName(fileDownloadName);
    }

    private String filePath;

    /**
     * 获取文件路径
     *
     * @return 文件路径
     */
    public String getFilePath() {
        return filePath;
    }

    @Override
    protected void writeFile(HttpServletResponse response) throws IOException {
        int status = 0;
        byte[] b = new byte[1024];
        FileInputStream in = null;
        ServletOutputStream out2 = null;
        String fileName;
        if (StringUtils.isEmpty(getFileDownloadName())) {
            File tempFile = new File(this.filePath);
            fileName = tempFile.getName();
        } else {
            fileName = getFileDownloadName();
        }
        try {
            response.setHeader("content-disposition", "attachment; filename="
                    + java.net.URLEncoder.encode(fileName, "UTF-8"));
            in = new FileInputStream(this.filePath);
            out2 = response.getOutputStream();
            while (status != -1) {
                status = in.read(b);
                out2.write(b);
            }
            out2.flush();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (in != null)
                in.close();
            if (out2 != null)
                out2.close();
        }
    }
}
